package com.ggk911.pharmacy_system.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ggk911.pharmacy_system.entity.DTO.SupplierDrugDTO;
import com.ggk911.pharmacy_system.entity.DrugInfo;
import com.ggk911.pharmacy_system.entity.Supplier;
import com.ggk911.pharmacy_system.entity.SupplierDrug;
import com.ggk911.pharmacy_system.service.impl.DrugInfoServiceImpl;
import com.ggk911.pharmacy_system.service.impl.DrugPriceServiceImpl;
import com.ggk911.pharmacy_system.service.impl.SupplierDrugServiceImpl;
import com.ggk911.pharmacy_system.service.impl.SupplierServiceImpl;
import com.ggk911.pharmacy_system.util.RestResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 供应商提供药品控制层
 *
 * @author ggk-911
 * @version 1.0 2023/3/9 15:26
 */
@RestController
@CrossOrigin
@Slf4j
@RequiredArgsConstructor
@RequestMapping("/supplierDrug")
@Api("供应商提供药品控制层")
public class SupplierDrugController {
    private final SupplierDrugServiceImpl service;
    private final SupplierServiceImpl supplierService;
    private final DrugInfoServiceImpl drugInfoService;

    //GET查询
    @GetMapping("/queryAll")
    public RestResult queryAll(@RequestParam(defaultValue = "1") Integer page,
                               @RequestParam(defaultValue = "10") Integer size,
                               @ApiParam("供应商编号") Integer supplierId,
                               @ApiParam("药品编号") Integer drugInfoId,
                               @RequestParam(defaultValue = "") @ApiParam("药品名称，别名关键字") String drugName,
                               @RequestParam(defaultValue = "") @ApiParam("制造商关键字") String manufacturer,
                               @RequestParam(defaultValue = "") @ApiParam("适应症关键字") String indications,
                               @RequestParam(defaultValue = "") @ApiParam("药品国家代码搜索") String nationalCode,
                               @RequestParam(defaultValue = "") @ApiParam("批准文号搜索") String approvalNo,
                               @RequestParam(defaultValue = "") @ApiParam("搜索关键供应商名称") String supplierName,
                               @RequestParam(defaultValue = "") @ApiParam("搜索关键供应商地址") String supplierAddr) {
        Page<SupplierDrug> supplierDrugPage = new Page<>(page, size);
        QueryWrapper<SupplierDrug> wrapper = new QueryWrapper<>();

        wrapper.like(supplierId != null, "supplier_id", supplierId);//搜索供应商编号
        wrapper.like(!"".equals(supplierName), "supplier.supplier_name", supplierName);//搜索供应商名称
        wrapper.like(!"".equals(supplierAddr), "supplier.supplier_addr", supplierAddr);//供应商地址
        wrapper.like(drugInfoId != null, "drug_info_id", drugInfoId);//搜索药品编号
        wrapper.and(!"".equals(drugName), a -> a.like("drug_info.drug_info_name", drugName).or().like("drug_info.drug_info_alias", drugName));//搜索药品名称
        wrapper.like(!"".equals(manufacturer), "drug_info.drug_info_manufacturer", manufacturer);//制造商
        wrapper.like(!"".equals(indications), "drug_info.drug_info_indications", indications);//适应症
        wrapper.like(!"".equals(nationalCode), "drug_info.drug_info_national_code", nationalCode);//国家代码
        wrapper.like(!"".equals(approvalNo), "drug_info.drug_info_approval_no", approvalNo);//药品批准文号

        service.page(supplierDrugPage, wrapper);

        return RestResult.ok("查询成功", supplierDrugPage);
    }

    //PUT添加
    @PutMapping("/insert")
    public RestResult insert(SupplierDrug supplierDrug) {
        try {
            QueryWrapper<SupplierDrug> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("supplier_id", supplierDrug.getSupplierId());
            queryWrapper.eq("drug_info_id", supplierDrug.getDrugInfoId());

            if (service.getOne(queryWrapper) != null) {
                return RestResult.error("添加失败，重复");
            }
            if (service.save(supplierDrug)) {
                log.info("supplierDrugInsert：" + supplierDrug.toString());
                return RestResult.ok("添加成功，返回编号：" + supplierDrug.getSupplierDrugId(), supplierDrug.getSupplierDrugId());
            }
        } catch (Exception e) {
            log.error(String.valueOf(e.getCause()));
            return RestResult.error("添加失败" + e.getCause());
        }
        return RestResult.error("添加失败");
    }

    //DELETE删除
    @DeleteMapping("/delete")
    public RestResult delete(Integer id) {
        if (service.removeById(id)) {
            return RestResult.ok("删除成功");
        }
        return RestResult.error("删除失败");
    }

    //POST修改
    @PostMapping("/update")
    public RestResult update(SupplierDrug supplierDrug) {
        if (service.updateById(supplierDrug)) {
            return RestResult.ok("修改成功");
        }
        return RestResult.error("修改失败");
    }

    //POST表格导入
    @SneakyThrows
    @PostMapping("/importExcel")
    public RestResult importExcel(MultipartFile file) {

        //逻辑暂时放在controller
        if (file.isEmpty()) {
            throw new RuntimeException("上传文件为空");
        }
        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(1);
        importParams.setHeadRows(1);
        InputStream inputStream = file.getInputStream();
        List<SupplierDrugDTO> list = ExcelImportUtil.importExcel(inputStream, SupplierDrugDTO.class, importParams);
        //拿到要导入的信息长度
        int size1 = list.size();
        inputStream.close();
        List<SupplierDrug> drugDTOList = new ArrayList<>();
        list.forEach(item -> {
            //查询是否重复
//            Supplier supplierTest = service.selectBySupplierLicense(item.getSupplierLicense());
            //判断空 重复 重复要判断数据库里的重复和这个supplierList里的重复
            System.out.println(item);
            boolean a = item.getSupplierDrugPrice() != null && item.getSupplierLicense() != null && !"".equals(item.getSupplierLicense()) && item.getDrugInfoNationalCode() != null && !"".equals(item.getDrugInfoNationalCode());
            if (a) {
                //可以找到它们
                Supplier supplier = supplierService.selectBySupplierLicense(item.getSupplierLicense());
                DrugInfo drugInfo = drugInfoService.selectByDrugInfoNationalCode(item.getDrugInfoNationalCode());
                boolean b = supplier != null && drugInfo != null;
                if (b) {
                    //数据库重复
                    QueryWrapper<SupplierDrug> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("supplier_id", supplier.getSupplierId());
                    queryWrapper.eq("drug_info_id", drugInfo.getDrugInfoId());
                    if (service.getOne(queryWrapper) == null) {
                        //sL重复判断标志
                        boolean flag = true;
                        //遍历sL
                        for (int i = 0; i < drugDTOList.size(); i++) {
                            //sL里有重复就直接false且跳出
                            if (drugDTOList.get(i).getDrugInfoId() != drugInfo.getDrugInfoId()) {
                                if (drugDTOList.get(i).getSupplierId() != supplier.getSupplierId()) {
                                    flag = false;
                                    break;
                                }
                            }
                        }
                        //判断重复
                        if (flag) {
                            drugDTOList.add(new SupplierDrug(null, drugInfo.getDrugInfoId(), supplier.getSupplierId(), item.getSupplierDrugPrice(), null, null));
                        }
                    }
                }


            }
        });
        //筛选后的长度
        int size = drugDTOList.size();
        if (size == 0) return RestResult.error("表中无数据或数据重复");
        if (service.saveBatch(drugDTOList)) {
            return RestResult.ok("批量导入成功，总：" + size1 + ",成功导入：" + size);
        }
        return RestResult.error("批量导入失败");
    }
}
